import { Directive, EventEmitter, Input, Output, HostListener, ElementRef, OnInit, OnDestroy } from '@angular/core';



declare var $: any;

@Directive({ selector: '[st-sort]' })

export class stSortDirective {

  // @Input('st-sort') public stSort:string;

  @Input('st-sort') public stSort: any;

  @Input('st-sort-data') public data: any;


  @Output() public sortChanged: EventEmitter<any> = new EventEmitter();



  constructor(private el: ElementRef) {
    // console.log(this.stSort);


  }

  column: any = {
    sortType: '',
    sort: ''
  };

  ngOnInit() {

    let ele: any = $(this.el.nativeElement);

    if (this.stSort.sort) {

      this.column.sort = this.stSort.name;

      if (this.data.sort == this.column.sort) {

        this.column.sortType = this.data.sortType;

        if (this.column.sortType == 'desc') {

          this.toggelClass(ele, 'st-sort-descent');


        } else if (this.column.sortType == 'asc') {

          this.toggelClass(ele, 'st-sort-ascent');

        } else {

          this.toggelClass(ele, '');
        }

      }

    } else {
      $(this.el.nativeElement).removeAttr('st-sort');
    }

    // 是否
    /*if(this.stSort.show && this.stSort.show === true){
  
      console.log('remove');
  
      $(this.el.nativeElement).remove();
    }*/

  }


  toggelClass(_ele, _sortClass) {

    if (_ele.hasClass('st-sort-descent')) {

      _ele.removeClass('st-sort-descent');
    }

    if (_ele.hasClass('st-sort-ascent')) {

      _ele.removeClass('st-sort-ascent');
    }

    // if(_sortClass == ''){
    //    this.column.sortType = '';
    // }

    _ele.addClass(_sortClass);

  }

  toggel(_ele) {

    // desc
    if (_ele.hasClass('st-sort-descent')) {

      _ele.removeClass('st-sort-descent');

      this.column.sortType = 'asc';
      _ele.addClass('st-sort-ascent');
    }
    // asc
    else if (_ele.hasClass('st-sort-ascent')) {

      _ele.removeClass('st-sort-ascent');

      this.column.sortType = '';
      // _ele.addClass('');
    }
    // ''
    else {
      this.column.sortType = 'desc';
      _ele.addClass('st-sort-descent');
    }


  }

  OnDestroy() { }



  @HostListener('click', ['$event']) onToggleSort(event: any): void {
    if (event) {
      event.preventDefault();
    }

    if (!this.stSort.sort) {
      return;
    }

    let ele: any = $(this.el.nativeElement);



    if (this.column) {

      this.toggel(ele);

    }
    // 去除其他的排序
    $(this.el.nativeElement).siblings().removeClass('st-sort-ascent');
    // 去除其他的排序
    $(this.el.nativeElement).siblings().removeClass('st-sort-descent');

    console.log(this.column);

    console.log(this.data);

    if (this.column.sortType == '') {
      this.data.sort = "";
      this.data.sortType = "";

    } else {

      Object.assign(this.data, this.column);
    }

    console.log(this.data);

    this.sortChanged.emit(this.column);
  }
}

